import SwiftUI
import CoreGraphics
import SPGlassKit

public struct GlassGalleryExample: GlassExample {
    public static let componentID = "glass-gallery"

    public init() {}

    public var body: some View {
        VStack(alignment: .leading, spacing: 8) {
            Text("Sample data · gradients generated in code, one slow image and one failing image.")
                .font(.caption)
                .foregroundStyle(.secondary)
                .padding(.horizontal)
            GlassGallery(items: Self.items, cacheCapacity: 12)
        }
    }

    private struct SampleLoadingError: Error {}

    static let items: [GlassGalleryItem] = {
        let names = ["Dawn", "Lagoon", "Orchard", "Ember", "Glacier", "Dusk", "Moss", "Coral", "Slate", "Saffron", "Iris", "Tundra"]
        var items = names.enumerated().map { index, name in
            GlassGalleryItem(id: "gradient-\(index)", description: "\(name) gradient", loadCGImage: {
                // Stands in for decoding a file; the sleep makes cancellation observable while scrolling.
                try await Task.sleep(for: .milliseconds(index == 3 ? 1_500 : 120))
                return try gradient(hue: Double(index) / Double(names.count))
            })
        }
        items.insert(GlassGalleryItem(id: "local-symbol", description: "Local symbol image", image: Image(systemName: "mountain.2.fill")), at: 1)
        items.insert(GlassGalleryItem(id: "broken", description: "An image that fails to load", load: { throw SampleLoadingError() }), at: 5)
        return items
    }()

    /// Draws a diagonal two-colour gradient into a bitmap.
    nonisolated static func gradient(hue: Double, side: Int = 256) throws -> CGImage {
        let space = CGColorSpaceCreateDeviceRGB()
        guard let context = CGContext(data: nil, width: side, height: side, bitsPerComponent: 8, bytesPerRow: 0, space: space, bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue) else {
            throw SampleLoadingError()
        }
        let colors = [rgb(hue: hue), rgb(hue: (hue + 0.18).truncatingRemainder(dividingBy: 1))] as CFArray
        guard let gradient = CGGradient(colorsSpace: space, colors: colors, locations: [0, 1]) else {
            throw SampleLoadingError()
        }
        context.drawLinearGradient(gradient, start: .zero, end: CGPoint(x: side, y: side), options: [])
        guard let image = context.makeImage() else { throw SampleLoadingError() }
        return image
    }

    /// A saturated colour for a hue in 0…1, without any platform colour type.
    nonisolated private static func rgb(hue: Double) -> CGColor {
        let sector = hue * 6
        let x = 1 - abs(sector.truncatingRemainder(dividingBy: 2) - 1)
        let (r, g, b): (Double, Double, Double) = switch Int(sector) % 6 {
        case 0: (1, x, 0)
        case 1: (x, 1, 0)
        case 2: (0, 1, x)
        case 3: (0, x, 1)
        case 4: (x, 0, 1)
        default: (1, 0, x)
        }
        return CGColor(red: 0.25 + 0.6 * r, green: 0.25 + 0.6 * g, blue: 0.25 + 0.6 * b, alpha: 1)
    }
}

#Preview("GlassGallery") { GlassGalleryExample().glassTheme(.crystal) }
